var $table = $('#table');
var URI_LIST = "/sec/user/list";
var URL_NAME_CHECK = "/sec/user/check";
var URI_CREATE = "/sec/user/create";
var URI_UPDATE = "/sec/user/update/";
var URI_DEL = "/sec/user/delete/";
var URI_DETAIL = "/sec/user/detail/";
var URI_INITPWD = "/sec/user/initPwd/";
var createFrom = "#SecUsercreateForm";
var updateForm = "#SecUserupdateForm";
var idField = "uid";
var createValidation = null;
var updateValidation = null;
var fieldCloumns = [
    {field: 'ck', checkbox: true},
    {field: 'avater', title: '头像', formatter: avaterFormatter},
    {field: 'loginName', title: '登录名'},
    {field: 'nickName', title: '昵称'},
    {field: 'gender', title: '性别', formatter: 'genderFormatter'},
    {field: 'mobile', title: '手机号'},
    {field: 'email', title: '邮箱'},
    {field: 'pwdEndDate', title: '密码有效日期'},
    {field: 'useState', title: '是否禁用', formatter: 'useStateFormatter'},
    {field: 'uid', title: '操作', align: 'center', formatter: 'actionFormatter', events: 'actionEvents', clickToSelect: false}
]
$(function () {
    $table.bootstrapTable({
        url: URI_LIST,
        detailFormatter: 'detailFormatter',
        idField: idField,
        toolbar: '#toolbar',
        columns: fieldCloumns
    });
});

function avaterFormatter(value, index, row) {
    if (value && value.length > 10) {
        return "<img style='width: 32px;' src='" + value + "' />";
    } else {
        return "<img style='width: 32px;' src='/images/default.png' />";
    }
}

function genderFormatter(value, index, row) {
    if (value == 1) {
        return "男";
    }
    if (value == 0) {
        return "女";
    }
    if (value == -1) {
        return "未知";
    }
    return "-";
}

function useStateFormatter(value, index, row) {
    if (value == 1) {
        return "正常";
    }
    if (value == -1) {
        return "待审";
    }
    if (value == 0) {
        return "禁用";
    }
    return "-";
}

function initValidate(formId) {
    var validator = $(formId).validate({
        rules: {
            loginName: {required: true, maxlength: 100, remote: URL_NAME_CHECK},
            nickName: {required: true, maxlength: 100},
            gender: {required: true, maxlength: 2},
            mobile: {required: true, maxlength: 20},
            email: {required: true, maxlength: 100, email: true},
            pwdEndDate: {required: true, date: true}
        }
    });
    return validator;
}

function detailFormatter(index, row) {
    $.get(URI_DETAIL + row.uid + ".html", function (resp) {
        $("tr[data-index=" + index + "]").next(".detail-view").children("td").html(resp);
    });
}

// 格式化操作按钮
function actionFormatter(value, row, index) {
    return [
        '<a class="update" href="javascript:;" onclick="updateAction(' + value + ')" data-toggle="tooltip" title="Edit"><i class="glyphicon glyphicon-edit"></i></a>　',
        '<a class="delete" href="javascript:;" onclick="deleteAction(' + value + ')" data-toggle="tooltip" title="Remove"><i class="glyphicon glyphicon-remove"></i></a>'
    ].join('');
}

// 新增
function createAction() {
    loadDialog("#rolesModal", "新增", URI_CREATE + ".html", function () {
        initMaterialInput();
        createValidation = initValidate(createFrom)
        $(createFrom).ajaxForm({
            target: '#btn-SecUser-submit',   // target element(s) to be updated with server response
            dataType: 'json',
            url: URI_CREATE,
            beforeSubmit: function (formData, jqForm, options) {
                return createValidation.valid();
            },
            success: function (result, statusText, xhr, $form) {
                if (result.code != "0000") {
                    showMessage(result.code || result.desc, "error");
                } else {
                    $("#rolesModal").modal("hide");
                    showMessage("创建成功");
                    $table.bootstrapTable('refresh');
                }
            }
        });
    })
}

// 编辑
var updateDialog;

function updateAction(value) {
    var rows = getRows(value);
    if (rows.length != 1) {
        showMessage("请选择一条记录！", "error");
    } else {
        loadDialog("#rolesModal", "编辑", URI_UPDATE + rows[0].uid + ".html", function () {
            initMaterialInput();
            updateValidation = initValidate(updateForm)
            $(updateForm).ajaxForm({
                target: '#btn-SecUser-update',   // target element(s) to be updated with server response
                dataType: 'json',
                url: URI_UPDATE + rows[0].uid,
                beforeSubmit: function (formData, jqForm, options) {
                    return updateValidation.valid();
                },
                success: function (result, statusText, xhr, $form) {
                    if (result.code != "0000") {
                        showMessage(result.code || result.desc, "error");
                    } else {
                        $("#rolesModal").modal("hide");
                        $table.bootstrapTable('refresh');
                    }
                }
            });
        });
    }
}

// 删除
var deleteDialog;

function deleteAction(value) {
    var rows = getRows(value);
    if (rows.length == 0) {
        showMessage("请选择一条记录！", "error");
    } else {
        deleteDialog = $.confirm({
            type: 'red',
            animationSpeed: 300,
            title: false,
            content: '确认删除该记录吗？',
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'waves-effect waves-button',
                    action: function () {
                        var ids = new Array();
                        for (var i in rows) {
                            ids.push(rows[i].uid);
                        }
                        $.ajax({
                            type: 'post',
                            url: URI_DEL + ids.join("-"),
                            success: function (result) {
                                if (result.code != "0000") {
                                    showMessage(result.desc || result.code, "error");
                                } else {
                                    deleteDialog.close();
                                    showMessage("删除成功");
                                    $table.bootstrapTable('refresh');
                                }
                            }
                        });
                    }
                },
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    }
}

function roleAction(value) {
    var rows = getRows(value);
    if (rows.length != 1) {
        showMessage("请选择一条记录！", "error");
    } else {
        loadDialog("#rolesModal", "赋予角色", "/sec/user/role.html?uid=" + rows[0].uid, function () {
            $("#SecUserRoleForm").ajaxForm({
                target: '#btn-SecUser-role',
                dataType: 'json',
                url: "/sec/user/role",
                success: function (result, statusText, xhr, $form) {
                    if (result.code != "0000") {
                        showMessage(result.code || result.desc, "error");
                    } else {
                        $("#rolesModal").modal("hide");
                        showMessage("设置角色成功!")
                    }
                }
            });
        });
    }
}

function groupAction(value) {
    var rows = getRows(value);
    if (rows.length != 1) {
        showMessage("请选择一条记录！", "error");
    } else {
        loadDialog("#rolesModal", "设置分组", "/sec/user/group.html?uid=" + rows[0].uid, function () {
            $("#SecUserGroupForm").ajaxForm({
                target: '#btn-SecUser-group',
                dataType: 'json',
                url: "/sec/user/group",
                success: function (result, statusText, xhr, $form) {
                    if (result.code != "0000") {
                        showMessage(result.code || result.desc, "error");
                    } else {
                        $("#rolesModal").modal("hide");
                        showMessage("设置分组成功");
                    }
                }
            });
        });
    }
}

function initPwd(value) {
    var rows = getRows(value);
    if (rows.length == 0) {
        showMessage("请选择一条记录！", "error");
    } else {
        $.ajax({
            url: URI_INITPWD + rows[0].uid,
            headers: headers,
            type: "post",
            success: function (result) {
                if (result.code != "0000") {
                    showMessage(result.code || result.desc, "error");
                } else {
                    showMessage("密码已重置!")
                }
            }
        });
    }
}

function loadDialog(selectEL, title, loadURI, success) {
    $(selectEL).find(".modal-title").html(title);
    $(selectEL).find('.modal-body').load(loadURI, function (response, status, xhr) {
        $('.selectpicker').selectpicker({
            noneSelectedText: "--请选择--",
            selectOnTab: true,
            liveSearch: true
        });
        $(selectEL).modal("show");
        if (success) {
            success();
        }
    });
}

function getRows(value) {
    var rows = []
    if (value) {
        rows.push($table.bootstrapTable('getRowByUniqueId', value));
    } else {
        rows = $table.bootstrapTable('getSelections');
    }
    return rows;
}